<template>
    <div>
        <basic-container>
            <div class="app-container">
                <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
                    <el-form-item label="设备名称">
                        <el-select v-model="queryParams.facility_id" placeholder="请选择" clearable @clear="getList">
                            <el-option v-for="item in roleOptions" :key="item.facility_id" :label="item.name"
                                :value="item.facility_id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <!-- <el-form-item label="设备编号">
                        <el-input v-model="queryParams.serials" placeholder="请输入设备编号" clearable @clear="getList" />
                    </el-form-item> -->
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                        <!-- <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button> -->
                    </el-form-item>
                </el-form>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="el-icon-plus" size="mini"
                            @click="handleAdd">新增记录</el-button>
                    </el-col>
                </el-row>
                <el-table v-loading="loading" :data="menuList" row-key="user_id" :default-expand-all="isExpandAll"
                    :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
                    <el-table-column prop="account" label="保养账户"></el-table-column>
                    <el-table-column prop="account_name" label="保养人" align="center"></el-table-column>
                    <el-table-column prop="serials" label="设备编号" align="center"></el-table-column>
                    <el-table-column label="保养照片" align="center">
                        <template slot-scope="scope">
                            <img :src="'data:image/png;base64,' + scope.row.image"
                                style="max-width: 100px; max-height: 100px;" @click="showImage(scope.row.image)">
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" label="设备名" align="center"></el-table-column>
                    <el-table-column prop="note" label="本次保养日志" align="center"></el-table-column>
                    <el-table-column prop="operate" label="本次保养时间" align="center"></el-table-column>
                    <!-- <el-table-column prop="remind" label="下次保养日期" align="center"></el-table-column> -->
                    <el-table-column label="操作" align="center" class-name="small-padding fixed-width">

                        <template slot-scope="scope">
                            <el-button size="mini" type="text" icon="el-icon-edit"
                                @click="handleUpdate(scope.row)">修改</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <pagination v-show="total > 0" :total="total" :page.sync="queryParams.index"
                    :limit.sync="queryParams.size" @pagination="getList" />
                <!-- 添加或修改菜单对话框 -->
                <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body
                    :close-on-click-modal="false">
                    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                        <el-row>
                            <el-col :span="19" v-if="title !== '修改记录'">
                                <el-form-item label="设备名称" prop="facility_id">
                                    <el-select v-model="form.facility_id" placeholder="请选择" clearable @clear="getList"
                                        style="width: 100%;" @change="valueChang">
                                        <el-option v-for="item in roleOptions" :key="item.facility_id"
                                            :label="item.name" :value="item.facility_id">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="19">
                                <el-form-item label="本次记录日志" prop="note">
                                    <el-autocomplete class="inline-input" style="width: 100%;" v-model="form.note"
                                        :fetch-suggestions="querySearch" placeholder="请输入内容"></el-autocomplete>
                                </el-form-item>
                            </el-col>
                            <el-col :span="19">
                                <el-form-item label="下次保养内容" prop="data">
                                    <el-input v-model="form.data" placeholder="请输入设备工站" />
                                </el-form-item>
                            </el-col>

                            <!-- <el-col :span="19">
                                <el-form-item label="设备添购日期" prop="remind">
                                    <el-date-picker v-model="form.remind" value-format="yyyy-MM-dd" type="date"
                                        placeholder="选择日期" style="width: 100%;">
                                    </el-date-picker>
                                </el-form-item>
                            </el-col> -->
                            <el-col :span="19">
                                <el-form-item label="本次保养日期" prop="operate">
                                    <el-date-picker v-model="form.operate" value-format="yyyy-MM-dd" type="date"
                                        placeholder="选择日期" style="width: 100%;">
                                    </el-date-picker>
                                </el-form-item>
                            </el-col>
                            <el-col :span="19">
                                <el-form-item label="下次保养日期" prop="remind">
                                    <el-date-picker v-model="form.remind" value-format="yyyy-MM-dd" type="date"
                                        placeholder="选择日期" style="width: 100%;">
                                    </el-date-picker>
                                </el-form-item>
                            </el-col>
                            <el-col :span="19">
                                <el-form-item label="保养照片" prop="image">
                                    <el-upload class="avatar-uploader" action="https://example.com/virtual-upload"
                                        :show-file-list="false" :on-change="handleFileChange">
                                        <img v-if="imgAddrsee" :src="imgAddrsee" class="avatar">
                                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                    </el-upload>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button type="primary" @click="submitForm">确 定</el-button>
                        <el-button @click="cancel">取 消</el-button>
                    </div>
                </el-dialog>
            </div>
        </basic-container>
        <el-dialog :visible.sync="imageDialogVisible" width="80%">
            <img :src="selectedImage" style="width: 100%;">
        </el-dialog>
    </div>
</template>

<script>
import {
    addupkeep,
    getupkeeplist,
    eidupkeep,
    dlefacility,
    upkeepInit,
} from "@/api/upkeep";
import { andonfacility } from "@/api/andon";
import { mapGetters } from "vuex";

export default {
    data() {
        return {

            imageDialogVisible: false,
            selectedImage: null,
            // 遮罩层
            loading: false,
            // 显示搜索条件
            showSearch: true,
            value1: [],
            total: 1,
            inMess: [],
            menuList: [],
            roleOptions: [],
            dataMuen: [
                {
                    value: 0,
                    label: "是",
                },
                {
                    value: 1,
                    label: "否",
                },
            ],
            options: [],
            restaurants: [],
            // 弹出层标题
            imgAddrsee: '',
            title: "",
            // 是否显示弹出层
            open: false,
            // 是否展开，默认全部折叠
            isExpandAll: false,
            // 重新渲染表格状态
            refreshTable: true,
            // 查询参数
            queryParams: {
                name: "",
                index: 1,
                facility_id: null,

            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                note: [
                    { required: true, message: "记录日志不能为空", trigger: "blur" },
                ],
                facility_id: [
                    { required: true, message: "设备名称不能为空", trigger: "blur" },
                ],
                operate: [
                    { required: true, message: "本次保养日期不能为空", trigger: "blur" },
                ],
                remind: [
                    { required: true, message: "下次保养日期不能为空", trigger: "blur" },
                ],
                time: [
                    { required: true, message: "设备添购时间不能为空", trigger: "blur" },
                ],
                expired: [
                    { required: true, message: "设备有效日期不能为空", trigger: "blur" },
                ],
            },
        };
    },
    created() {
        this.getList();
        // this.startPolling();
        this.gitandomID()
    },
    computed: {
        ...mapGetters(["userInfo", "menu"]),
    },
    beforeDestroy() {
        // this.stopPolling();
    },
    methods: {
        // startPolling() {
        //     this.pollingTimer = setInterval(this.getList, 10000); // 每10秒刷新一次（根据需要进行调整）
        // },
        // stopPolling() {
        //     clearInterval(this.pollingTimer);
        // },
        //获取设备Id号
        handleFileChange(file) {

            if (file.raw) {
                const reader = new FileReader();
                reader.onload = (event) => {
                    this.imgAddrsee = event.target.result;
                };
                reader.readAsDataURL(file.raw);
            }

            this.form.image = file.raw

        },
        gitandomID() {
            andonfacility().then((res) => {
                this.roleOptions = res.data.data
            })
        },
        // 匹配电话号码
        showImage(base64ImageData) {
            this.selectedImage = `data:image/png;base64,${base64ImageData}`;
            this.imageDialogVisible = true;
        },
        onPhoneInput(event) {
            let value = event;
            // 使用正则表达式过滤非数字字符
            value = value.replace(/\D/g, "");
            // 更新输入框的值
            this.form.phone = value;
        },
        /** 查询菜单列表 */
        getList() {
            this.loading = true;
            getupkeeplist(this.queryParams).then((response) => {

                this.menuList = response.data.data;
                this.total = response.data.count;
                this.loading = false;
            });
        },
        querySearch(queryString, cb) {
            var restaurants = this.restaurants;
            var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
            cb(results);
        },
        createFilter(queryString) {
            return (restaurant) => {
                const value = restaurant.value;
                return value && typeof value === 'string' && value.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
            }
        },
        valueChang() {
            this.getTisty()
        },
        getTisty() {
            let faciID = {
                facility_id: this.form.facility_id
            }
            upkeepInit(faciID).then(res => {
                let record = res.data

                this.restaurants = [{
                    "value": record.data,
                    "address": String(record.status)
                }]

            })
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.getList();
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                facility_id: null,
                operate: null,
                note: null,
                image: null,
                remind: null,
                data: null,
                upkeep_id: null
            };
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.queryParams = {
                name: "",
                index: 1,
                size: 10
            };
            this.getList();
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.open = true;
            this.reset();
            this.title = "新增记录";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {

            this.imgAddrsee = 'data:image/png;base64,' + row.image
            this.reset();
            this.form = row;
            this.open = true;
            this.title = "修改记录";
        },
        /** 提交按钮 */
        submitForm() {

            this.$refs["form"].validate((valid) => {
                if (valid) {
                    var formData = new FormData();
                    if (this.title == "新增记录") {
                        formData.append('facility_id', this.form.facility_id);
                        formData.append('operate', this.form.operate);
                        formData.append('note', this.form.note);
                        formData.append('image', this.form.image);
                        formData.append('remind', this.form.remind);
                        formData.append('data', this.form.data);
                        addupkeep(formData).then(() => {
                            this.$message({
                                message: "添加成功",
                                type: "success",
                            });
                            this.open = false;
                            this.getList();
                            this.reset();

                        });
                    } else {

                        formData.append('operate', this.form.operate);
                        formData.append('note', this.form.note);
                        formData.append('remind', this.form.remind);
                        formData.append('data', this.form.data);
                        formData.append('upkeep_id', this.form.upkeep_id);
                        eidupkeep(formData).then(() => {
                            this.$message({
                                message: "修改成功",
                                type: "success",
                            });

                            this.open = false;
                            this.getList();
                            this.reset();
                        });
                    }
                }
            });
        },

        /** 删除按钮操作 */
        handleDelete(row) {

            this.$confirm('是否确认删除名称为"' + row.name + '"的设备？').then(() => {
                this.form = row;
                dlefacility(this.form).then(() => {
                    this.$message({
                        message: "删除成功",
                        type: "success",
                    });
                    this.open = false;
                    this.getList();
                    this.reset();
                });
            })
                .catch(() => { });
        },
    },
};
</script>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
